import 'dart:io';
import 'dart:math';

import 'package:excel_utils/pages/cpc_report/cpc_file/cpc_file_page.dart';
import 'package:excel_utils/pages/cpc_report/cpc_luggage/cpc_report_page.dart';
import 'package:excel_utils/pages/customer_service/customer_service_page.dart';
import 'package:excel_utils/pages/daily/daily_report/daily_report_page.dart';
import 'package:excel_utils/pages/month_report/month_data_merging_page.dart';
import 'package:excel_utils/pages/week/week_report/week_report_page.dart';
import 'package:excel_utils/repository/constant.dart';
import 'package:excel_utils/service/DioManager.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // 随机数
  final Random random = Random();
  String _randomString = "";

  bool isLily = false;
  bool isKefu = false;
  bool isAll = false;

  @override
  void initState() {
    _randomString = random.nextInt(1000000).toString();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (!kIsWeb) {
        _checkNetwork();
      }
    });

    const name = String.fromEnvironment("typeName", defaultValue: "");
    print("参数名称：$name");
    if (name.isNotEmpty && name == "lily") {
      isLily = true;
    } else if (name.isEmpty || name == "kefu") {
      isKefu = true;
    } else if (name.isEmpty || name == "all") {
      isAll = true;
    }

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          // 下拉地址选择
          Container(
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                DropdownMenu(
                    label: const Text("选择环境"),
                    dropdownMenuEntries: const [
                      DropdownMenuEntry(value: "http://localhost:9090/", label: '本地环境'),
                      DropdownMenuEntry(value: "http://117.72.16.237:9090/", label: '生产环境'),
                    ],
                    onSelected: (value) {
                      Constant.notK8Url = value.toString();
                      Constant.notK8Url = value.toString();
                    }),
                SizedBox(
                    width: 200,
                    child: TextField(
                      decoration: InputDecoration(
                        hint: Text("自定义环境"),
                      ),
                      onChanged: (value){
                        Constant.notK8Url = value.toString();
                      },
                    )),
              ],
            ),
          ),
          Container(
            alignment: Alignment.center,
            child: buildMenu(),
          ),
        ],
      ),
    );
  }

  Widget buildMenu() {
    if (isLily) {
      return Wrap(
        spacing: 20,
        runSpacing: 20,
        children: [
          ElevatedButton(
            onPressed: () {
              Navigator.push(context, MaterialPageRoute(builder: (_) => CPCReportPage()));
            },
            child: Text("中邮报表"),
            style: ButtonStyle(
              minimumSize: WidgetStatePropertyAll(Size(150, 150)),
            ),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.push(context, MaterialPageRoute(builder: (_) => ChkFilePage()));
            },
            child: Text("中邮文件"),
            style: ButtonStyle(
              minimumSize: WidgetStatePropertyAll(Size(150, 150)),
            ),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.push(context, MaterialPageRoute(builder: (_) => MonthDataMergingPage()));
            },
            child: Text("月表格整合"),
            style: ButtonStyle(
              minimumSize: WidgetStatePropertyAll(Size(150, 150)),
            ),
          ),
        ],
      );
    } else if (isKefu) {
      // 客服使用
      return Wrap(
        spacing: 20,
        runSpacing: 20,
        children: [
          ElevatedButton(
            onPressed: () {
              Navigator.push(context, MaterialPageRoute(builder: (_) => CustomerServicePage()));
            },
            child: Text("数据录入"),
            style: ButtonStyle(
              minimumSize: WidgetStatePropertyAll(Size(150, 150)),
            ),
          )
        ],
      );
    } else if (isAll) {
      return Wrap(
        spacing: 20,
        runSpacing: 20,
        children: [
          ElevatedButton(
            onPressed: () {
              Navigator.push(context, MaterialPageRoute(builder: (_) => CPCReportPage()));
            },
            child: Text("中邮报表"),
            style: ButtonStyle(
              minimumSize: WidgetStatePropertyAll(Size(150, 150)),
            ),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.push(context, MaterialPageRoute(builder: (_) => ChkFilePage()));
            },
            child: Text("中邮文件"),
            style: ButtonStyle(
              minimumSize: WidgetStatePropertyAll(Size(150, 150)),
            ),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.push(context, MaterialPageRoute(builder: (_) => MonthDataMergingPage()));
            },
            child: Text("月表格整合"),
            style: ButtonStyle(
              minimumSize: WidgetStatePropertyAll(Size(150, 150)),
            ),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.push(context, MaterialPageRoute(builder: (_) => DailyReportPage()));
            },
            child: Text("日报表"),
            style: ButtonStyle(
              minimumSize: WidgetStatePropertyAll(Size(150, 150)),
            ),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.push(context, MaterialPageRoute(builder: (_) => WeekReportPage()));
            },
            child: Text("周报表"),
            style: ButtonStyle(
              minimumSize: WidgetStatePropertyAll(Size(150, 150)),
            ),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.push(context, MaterialPageRoute(builder: (_) => CustomerServicePage()));
            },
            child: Text("数据录入"),
            style: ButtonStyle(
              minimumSize: WidgetStatePropertyAll(Size(150, 150)),
            ),
          ),
        ],
      );
    } else {
      return Container(
        child: Text("请输入打包参数"),
      );
    }
  }

  showSnackBar(Text msg) {
    ScaffoldMessenger.of(context)
      ..hideCurrentSnackBar()
      ..showSnackBar(SnackBar(content: msg));
  }

  Future<void> _checkNetwork() async {
    try {
      final response = await DioManager().get(path: "https://www.baidu.com");
      if (response.statusCode == 200) {
        // 检测在线 SDK 版本
        DateTime currentDate = DateTime.now();
        DateTime comparisonDate = DateTime(2026, 06, 22, 18, 0, 0);
        if (currentDate.isAfter(comparisonDate)) {
          showDialog(
              context: context,
              barrierDismissible: false,
              builder: (context) {
                return AlertDialog(
                  content: Text("内置sdk 异常，请更新sdk"),
                  actions: [
                    TextButton(
                        onPressed: () {
                          exit(0);
                        },
                        child: Text("确定"))
                  ],
                );
              });
        }
      } else {
        showDialog(
            context: context,
            barrierDismissible: false,
            builder: (context) {
              return AlertDialog(
                content: Text("网络异常,请检查网络设置"), // project_manag
                actions: [
                  TextButton(
                      onPressed: () {
                        Navigator.pop(context);
                        _checkNetwork();
                      },
                      child: Text("确定"))
                ],
              );
            });
      }
    } catch (e) {
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) {
            return AlertDialog(
              content: Text("网络异常,请检查网络设置"),
              actions: [
                TextButton(
                    onPressed: () {
                      Navigator.pop(context);
                      _checkNetwork();
                    },
                    child: Text("确定"))
              ],
            );
          });
    }
  }
}
